<template>
  <el-config-provider :locale="zhCn" :message="config">
    <router-view></router-view>
  </el-config-provider>
</template>

<script setup lang="ts">
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import { onBeforeMount, ref } from 'vue'
import { autoLoginHttpRequest, sysSettingHttpRequest } from './services/api/home'
import { useHomeStore, type UserInfo } from './stores/home'
import { get, set } from 'vue-cookies'
import { loadAllCategoryHttpRequest } from './services/api/category'
import { useCategoryStore } from './stores/category'
import FingerprintJS from '@fingerprintjs/fingerprintjs'
import { useSysSettingStore } from './stores/sysSetting'
const homeStore = useHomeStore()
const sysSettingStore = useSysSettingStore()
const categoryStore = useCategoryStore()
//当前配置 message 可以让你使用的当前组件库的消息框上限提示为1次 不会重复叠加显示
const config = ref({
  max: 1
})

//校验自动登录(如果长时间没有登录则会失效)
//如果当你快距离过期时间小于1天他会重新续期
const autoLogin = async () => {
  const token = get('token')
  console.log(token)
  if (!token) {
    return
  }
  const res = await autoLoginHttpRequest()
  saveLoginInfo(res.data)
}

const saveLoginInfo = (loginInfo: UserInfo) => {
  if (!loginInfo) {
    homeStore.saveUserInfo(null)
  } else {
    homeStore.saveUserInfo(loginInfo)
  }
}

//首页分类列表
let categoryList = []
const categoryMap = {} as Record<string, any>

const getAllCategoryList = async () => {
  const res = await loadAllCategoryHttpRequest()
  if (!res) {
    return
  }
  categoryList = res.data
  res.data.forEach((ele) => {
    // 保存成键对值类型
    categoryMap[ele.categoryCode] = ele
    ele.children?.forEach((sub) => {
      categoryMap[sub.categoryCode] = sub
    })
  })

  categoryStore.saveCategoryMap(categoryMap as any)
  categoryStore.saveCategoryList(categoryList)
}

//获取浏览器唯一标识
const getDeviceId = async () => {
  //从Cookie中获取唯一标识
  let deviceId = get('deviceId')
  //如果没有读取到证明是第一次进入需要生成唯一标识
  if (!deviceId) {
    //使用工具生成
    const fpPromise = await FingerprintJS.load()
    const res = await fpPromise.get()
    deviceId = res.visitorId
    //设置Cookie
    set('deviceId', deviceId)
  } else {
    homeStore.saveDeviceId(deviceId)
  }
}

//获取系统设置信息
const getSysSettingInfo = async () => {
  const res = await sysSettingHttpRequest()
  sysSettingStore.saveSysSetting(res.data)
}

onBeforeMount(() => {
  autoLogin()
  getAllCategoryList()
  getDeviceId()
  getSysSettingInfo()
})
</script>

<style lang="less" scoped></style>
